import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:extended_image/extended_image.dart' as ex;
import 'package:flutter/material.dart';
import 'package:image_editor/image_editor.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/log_util.dart';

import 'safe_scaffold.dart';

///裁剪图片的页面
class CropImgPage extends StatefulWidget {
  const CropImgPage({
    Key? key,
    required this.img,
    this.aspectRatios = 1,
    this.fileName,
  }) : super(key: key);

  final File img;
  final double aspectRatios;
  final String? fileName;

  @override
  _CropImgPageState createState() => _CropImgPageState();
}

class _CropImgPageState extends State<CropImgPage> {
  GlobalKey<ex.ExtendedImageEditorState>? _editorKey;

  @override
  void initState() {
    super.initState();
    _editorKey = GlobalKey<ex.ExtendedImageEditorState>();
  }

  @override
  void dispose() {
    super.dispose();
    _editorKey?.currentState?.dispose();
    _editorKey = null;
  }

  ///裁剪并返回图片文件
  Future<void> _cropImage() async {
    try {
      loading(context);

      debug('需要处理的图片路径:${widget.img.path}');

      final ui.Rect? _cropRect = _editorKey?.currentState?.getCropRect();

      final Uint8List? _imgData = _editorKey?.currentState?.rawImageData;

      final ImageEditorOption _option = ImageEditorOption();

      _option.addOption(ClipOption.fromRect(_cropRect!));

      final Uint8List? result = await ImageEditor.editImage(image: _imgData!, imageEditorOption: _option);

      ///裁剪文件名
      final String temp = widget.img.path.split('/').last;
      final File file = File(
        widget.img.path.replaceAll(
          temp,
          '${widget.fileName ?? DateTime.now().millisecondsSinceEpoch}.png',
        ),
      );

      file.writeAsBytesSync(result!);

      close(context);
      close(context, value: file);
    } catch (e) {
      error('裁剪图片失败:$e');
      close(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    const double size = 70;

    return SafeScaffold(
      body: Stack(
        children: <Widget>[
          ex.ExtendedImage(
            image: ex.ExtendedFileImageProvider(widget.img, cacheRawData: true),
            fit: BoxFit.contain,
            mode: ex.ExtendedImageMode.editor,
            extendedImageEditorKey: _editorKey,
            initEditorConfigHandler: (ex.ExtendedImageState? state) {
              return ex.EditorConfig(
                maxScale: 20.0,
                cropRectPadding: const EdgeInsets.all(20.0),
                hitTestSize: 20.0,
                cropAspectRatio: widget.aspectRatios,
              );
            },
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Padding(
              padding: const EdgeInsets.only(bottom: 50),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  SizedBox(
                    width: size,
                    height: size,
                    child: TextButton(
                      onPressed: () => pop(
                        context,
                      ),
                      child: const Icon(Icons.close_rounded, color: Colors.white, size: 30),
                      style: TextButton.styleFrom(
                        backgroundColor: Colors.red,
                        padding: EdgeInsets.zero,
                        shape: const StadiumBorder(),
                      ),
                    ),
                  ),
                  SizedBox(
                    width: size,
                    height: size,
                    child: TextButton(
                      onPressed: () async => await _cropImage(),
                      child: const Icon(Icons.check_rounded, color: Colors.white, size: 30),
                      style: TextButton.styleFrom(
                        backgroundColor: Colors.green,
                        padding: EdgeInsets.zero,
                        shape: const StadiumBorder(),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
